package org.contextsensitivetodo.todoview.adapter;

import java.util.ArrayList;

import org.contextsensitivetodo.R;
import org.contextsensitivetodo.todoview.model.TodoItem;
import org.contextsensitivetodo.todoview.views.TodoListItem;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public class ToDoListAdapter extends BaseAdapter {
	
	private ArrayList<TodoItem> todos;
	private Context context;

	
	public ToDoListAdapter(ArrayList<TodoItem> todos, Context context) {
		super();
		this.todos = todos;
		this.context = context;
	}

	public int getCount() {
		return todos.size();
	}
	

	public TodoItem getItem(int position) {
		return todos.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		TodoListItem listItem;
		if(convertView == null){
			listItem = (TodoListItem) View.inflate(this.context, R.layout.todolistitem, null);
		}else{
			listItem = (TodoListItem)convertView;
		}
		listItem.setTodoItem(todos.get(position));
		return listItem;
	}

	public void forceReload() {
		notifyDataSetChanged();
		
	}

	public void toggleTaskCompleteAtPosition(int position) {
		this.getItem(position).setComplete(!this.getItem(position).isComplete());
		notifyDataSetChanged();
	}

	public Long[] removeCompletedTasks() {
		ArrayList<TodoItem> completeditems = new ArrayList<TodoItem>();
		ArrayList<Long> completedIds = new ArrayList<Long>();
		for (TodoItem item : todos) {
			if(item.isComplete()){
				completeditems.add(item);
				completedIds.add(item.getId());
			}
		}
		todos.removeAll(completeditems);
		notifyDataSetChanged();
		
		return completedIds.toArray(new Long[]{});
	}

}
